package com.example.demo.ui.home;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.demo.R;
import com.example.demo.bese.BaseActivity;
import com.example.demo.databinding.ActivityUserRetrievalBinding;
import com.example.demo.model.BaseBean;
import com.example.demo.model.UserBean;
import com.example.demo.ui.home.adapter.UserAdapter;
import com.example.demo.util.MyDialog;
import com.example.demo.util.MyJson;
import com.example.demo.util.PinyinComparator;
import com.example.demo.util.PinyinUtils;
import com.example.demo.util.ToastUtil;
import com.example.demo.view.TitleItemDecoration;
import com.example.library.utils.AssetsUtil;
import com.example.library.view.WaveSideBar;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author: xtxiaolu
 * @date: 2023/8/31
 * 描述: 用户检索列表
 */
public class UserRetrievalActivity extends BaseActivity {
    private ActivityUserRetrievalBinding binding;
    private UserAdapter userAdapter;

    /**
     * 根据拼音来排列RecyclerView里面的数据类
     */
    private PinyinComparator mComparator;
    private LinearLayoutManager manager;
    private TitleItemDecoration mDecoration;

    private List<UserBean> contactsList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityUserRetrievalBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        String rqsSrc = "UserList.json";
        String rqsJson = AssetsUtil.getAssetsJson(this, rqsSrc);
        BaseBean baseBean = MyJson.fromJson(rqsJson, BaseBean.class);
        List<UserBean> userList = MyJson.fromJson(MyJson.toJson(baseBean.getData()),
                new TypeToken<ArrayList<UserBean>>() {
                }.getType());

        mComparator = new PinyinComparator();
        Collections.sort(userList, mComparator);

        manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.recyclerView.setLayoutManager(manager);
        userAdapter = new UserAdapter(new ArrayList<>());
        binding.recyclerView.setAdapter(userAdapter);

        contactsList = filledData(userList);
        refreshAdapter(contactsList);

        userAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            UserBean item = (UserBean) adapter.getItem(position);
            int id = view.getId();
            if (id == R.id.llUserName) {
                ToastUtil.showShort("点击条目测试：Name " + item.getRealName());
            } else if (id == R.id.ivPhone) {
                String realName    = item.getRealName();
                String phoneNumber = item.getUserPhone();
                if (TextUtils.isEmpty(phoneNumber)) {
                    ToastUtil.showShort("联系人没有保留电话!");
                } else {
                    new MyDialog(this)
                            .setTitle("拨号")
                            .setMsg(realName + "\n" + phoneNumber + "\n" + "请确认要拨打的电话？")
                            .setNegativeButton(R.string.cancel, null)
                            .setPositiveButton(R.string.ok, v -> {
                                        Intent intent = new Intent(Intent.ACTION_DIAL);
                                        Uri ril = Uri.parse("tel:" + phoneNumber);
                                        intent.setData(ril);
                                        startActivity(intent);
                                    }
                            )
                            .show();
                }
            }
        });

        //设置右侧SideBar触摸监听
        binding.sideBar.setOnTouchLetterChangeListener(new WaveSideBar.OnTouchLetterChangeListener() {
            @Override
            public void onLetterChange(String letter) {
                //该字母首次出现的位置
                int position = userAdapter.getPositionForSection(letter.charAt(0));
                if (position != -1) {
                    manager.scrollToPositionWithOffset(position, 0);
                }
            }
        });
    }

    /**
     * 为RecyclerView填充数据
     *
     * @param date
     * @return
     */
    private List<UserBean> filledData(List<UserBean> date) {
        for (int i = 0; i < date.size(); i++) {
            //汉字转换成拼音
            String pinyin = PinyinUtils.getPingYin(date.get(i).getRealName());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                date.get(i).setLetters(sortString.toUpperCase());
            } else {
                date.get(i).setLetters("#");
            }
        }
        return date;
    }

    private void refreshAdapter(List<UserBean> contactsListBean) {
        // 根据a-z进行排序源数据
        Collections.sort(contactsListBean, mComparator);
        userAdapter.getData().clear();
        userAdapter.replaceData(contactsListBean);
        if (mDecoration == null) {
            mDecoration = new TitleItemDecoration(this, contactsList);
            //如果add两个，那么按照先后顺序，依次渲染。
            binding.recyclerView.addItemDecoration(mDecoration);
            binding.recyclerView.addItemDecoration(new DividerItemDecoration(UserRetrievalActivity.this, DividerItemDecoration.VERTICAL));
        }
    }
}